<?php

/**
 * 系统设置模型类
 *
 * @package    01CMS
 * @subpackage admin
 * @author     rolong at vip.qq.com
 * @version    1.0.0
 * @link       http://www.01cms.com
 */

class HtmlModel
{
    private $Db;

    function __construct ()
    {
        $this->Db = model('Db');
    }

    /**
     * 获取HTML
     * 
     * @param string $tplName
     * @return string
     * @access 	public
     */
    public static function getHtml ($tplName)
    {
        restore_error_handler();
        
        $style = Base::i()->Load->var['style'];
        $Smarty = lib('Smarty');
        $Smarty->compile_dir = APP_PATH . '/data/compile/' . Base::i()->c . '/' . Base::i()->m;
        if (! file_exists($Smarty->compile_dir))
        {
            makeDirs($Smarty->compile_dir);
        }
        $Smarty->plugins_dir = array(APP_PATH . '/plugin', SYS_PATH . '/plugin', SYS_PATH . '/lib/Smarty/plugins');
        $Smarty->template_dir = ROOT_PATH . '/template/' . $style;
        $Smarty->left_delimiter = '{:';
        $Smarty->assign_by_ref('i', Base::i());
        
        return $Smarty->fetch($tplName);
    }

    function indexHtml ($type = 'show')
    {
        $html = $this->getHtml(Base::i()->Load->var['homepageTemplateName']);
        
        if ($type == 'show')
        {
            echo $html;
        }
        else if ($type == 'write')
        {
            file_put_contents(ROOT_PATH . '/' . Base::i()->Load->var['homepageFileName'], $html);
        }
    }

    /**
     * 生成栏目HTML
     * 
     * @param int $id
     * @return void
     * @access public
     */
    function writeCategoryHtml ($id)
    {
        $Category = model('Category', $id);
        
        if (! empty($Category->data))
        {
            Base::i()->id = $id;
            Base::i()->data = $Category->data;
            
            if (empty($Category->allSonId))
            {
                $where = "categoryId = {$id}";
            }
            else
            {
                $where = "categoryId in ({$id},{$Category->allSonId})";
            }
            
            $pageSize = $Category->pageSize;
            
            $count = $this->Db->getOne("select count(*) as num from @@__archive_archive where pass = 1 AND {$where}");
            
            $pages = ceil($count / $pageSize);
            $page = 1;
            
            do
            {
                $start = $pageSize * ($page - 1);
                
                $lists = $this->Db->getRows("select * from @@__archive_archive where pass = 1 AND {$where} order by ordering desc limit {$start}, {$pageSize}");
                
                Base::i()->lists = model('Archive')->setArchiveFlag($lists);
                
                lib('StaticPages')->createLinks(array('fileId'=>'list', 'curPage'=>$page, 'pageSize'=>$pageSize, 'baseUrl'=>'/' . $Category->alias, 'totalPages'=>$pages));
                
                $html = $this->getHtml($Category->categoryTemplateName);
                
                $fileName = ($page == 1) ? 'index.html' : "list{$page}.html";
                
                $filePath = ROOT_PATH . Base::i()->Load->var['htmlSaveDir'] . '/' . $Category->alias;
                
                makeDirs($filePath);
                
                file_put_contents("{$filePath}/{$fileName}", $html);
                $page ++;
            } while ($page <= $pages);
        }
    }

    /**
     * 输出栏目HTML
     * 
     * @param int $id
     * @return void
     * @access public
     */
    function showCategoryHtml ($id, $start = 0)
    {
        $Category = model('Category', $id);
        
        if (! empty($Category->data))
        {
            Base::i()->id = $id;
            Base::i()->data = $Category->data;
            
            if (empty($Category->allSonId))
            {
                $where = "categoryId = {$id}";
            }
            else
            {
                $where = "categoryId in ({$id},{$Category->allSonId})";
            }
            
            $pageSize = $Category->pageSize;
            
            $count = $this->Db->getOne("select count(*) as num from @@__archive_archive where pass = 1 AND {$where}");
            
            $lists = $this->Db->getRows("select * from @@__archive_archive where pass = 1 AND {$where} order by ordering desc limit {$start}, {$pageSize}");
            
            Base::i()->lists = model('Archive')->setArchiveFlag($lists);
            
            $baseUrl = BOOT_URL . '/category/' . $id;
            
            lib('Pagination')->createLinks(array('baseUrl'=>$baseUrl, 'totalRows'=>$count, 'pageSize'=>$pageSize));
            
            echo $this->getHtml($Category->categoryTemplateName);
        }
        else
        {
            showError('404');
        }
    }

    /**
     * 生成文档HTML
     * 
     * @param int $id
     * @return void
     * @access public
     */
    function writeArchiveHtml ($id)
    {
        $Archive = model('Archive', $id);
        
        if (! empty($Archive->data))
        {
            $Category = model('Category', $Archive->categoryId);
            $Channel = model('Channel', $Category->channelId);
            
            $count = $this->Db->getOne("SELECT count(*) FROM @@__archive_channel_{$Channel->tableId} where archiveId={$id}");
            
            $archiveUrl = empty($Archive->fileName) ? $Category->archiveUrl : $Archive->fileName;
            
            $archiveUrl = str_replace('[id]', $Archive->id, $archiveUrl);
            $archiveUrl = str_replace('[alias]', $Category->alias, $archiveUrl);
            $archiveUrl = str_replace('%Y', date('Y', $Archive->addTime), $archiveUrl);
            $archiveUrl = str_replace('%m', date('m', $Archive->addTime), $archiveUrl);
            $archiveUrl = str_replace('%d', date('d', $Archive->addTime), $archiveUrl);
            
            $Archive->url = $archiveUrl;
            
            $baseName = basename($archiveUrl);
            $baseUrl = dirname($archiveUrl);
            $strrpos = strrpos($baseName, '.');
            $fileId = substr($baseName, 0, $strrpos);
            $fileExt = substr($baseName, $strrpos);
            
            makeDirs(ROOT_PATH . $baseUrl);
            
            $pagesConfig = array();
            
            $pagesConfig['firstFileName'] = $baseName;
            $pagesConfig['fileId'] = $fileId . '_';
            $pagesConfig['pageSize'] = 1;
            $pagesConfig['baseUrl'] = $baseUrl;
            $pagesConfig['fileExt'] = $fileExt;
            $pagesConfig['totalPages'] = $count;
            
            $this->Db->query("SELECT * FROM @@__archive_channel_{$Channel->tableId} where archiveId={$id}", 'archive');
            
            $page = 1;
            
            while ($data = $this->Db->getNextRow('archive'))
            {
                $pagesConfig['curPage'] = $page;
                
                foreach ($data as $k => $v)
                {
                    if (! in_array($k, array('id', 'archiveId', 'categoryId')))
                    {
                        $Archive->{$k} = $v;
                    }
                }
                
                Base::i()->show = $Archive;
                
                lib('StaticPages')->createLinks($pagesConfig);
                
                $templateName = empty($Archive->templateName) ? $Category->archiveTemplateName : $Archive->templateName;
                
                $html = $this->getHtml($templateName);
                
                $fileName = ($page == 1) ? $baseName : $pagesConfig['fileId'] . $page . $fileExt;
                
                $fileName = ROOT_PATH . $baseUrl . '/' . $fileName;
                
                file_put_contents($fileName, $html);
                
                $page ++;
            }
        }
    }

    /**
     * 输出文档HTML
     * 
     * @param int $id
     * @return void
     * @access public
     */
    function showArchiveHtml ($id, $start = 0)
    {
        
        $Archive = model('Archive', $id);
        
        if (isset($Archive->id) && $Archive->id > 0)
        {
            $Category = model('Category', $Archive->categoryId);
            $Channel = model('Channel', $Category->channelId);
            
            $data = $this->Db->getRows("SELECT * FROM @@__archive_channel_{$Channel->tableId} where archiveId={$id}");
            
            $count = count($data);
            
            $data = $data[$start];
            
            foreach ($data as $k => $v)
            {
                if (! in_array($k, array('id', 'archiveId', 'categoryId')))
                {
                    $Archive->{$k} = $v;
                }
            }
            
            Base::i()->show = $Archive;
            
            $baseUrl = BOOT_URL . '/archive/' . $id;
            
            lib('Pagination')->createLinks(array('baseUrl'=>$baseUrl, 'totalRows'=>$count, 'pageSize'=>1));
            
            $templateName = empty($Archive->templateName) ? $Category->archiveTemplateName : $Archive->templateName;
            
            echo $this->getHtml($templateName);
        
        }
        else
        {
            showError('404');
        }
    }

    /**
     * 输出单页文档HTML
     * 
     * @param int $id
     * @return void
     * @access public
     */
    function showSingleHtml ($id)
    {
        $Archive = model('Single', $id);
        if (isset($Archive->id) && $Archive->id > 0)
        {
            Base::i()->show = $Archive;
            echo $this->getHtml($Archive->template);
        }
        else
        {
            showError('404');
        }
    }

    /**
     * 生成单页文档HTML
     * 
     * @param string $ids
     * @return void
     * @access public
     */
    function writeSingleHtml ($ids)
    {
        $ids = explode(',', $ids);
        $i = 0;
        foreach ($ids as $id)
        {
            $Archive = model('Single', $id);
            if (isset($Archive->id) && $Archive->id > 0)
            {
                Base::i()->show = $Archive;
                $html = $this->getHtml($Archive->template);
                $filePath = ROOT_PATH . dirname($Archive->fileName);
                makeDirs($filePath);
                file_put_contents(ROOT_PATH . '/' . $Archive->fileName, $html);
            }
            $i ++;
        }
        return $i;
    }

    /**
     * 生成单页文档HTML
     * 
     * @param int $id
     * @return void
     * @access public
     */
    function writeAllSingleHtml ()
    {
        $this->Db->query("select id from @@__archive_single", 'singleId');
        $i = 0;
        while($single = $this->Db->getNextRow('singleId'))
        {
            $this->writeSingleHtml($single->id);
            $i ++;
        }
        return $i;
    }
}
